package com.lxl.hadoop.flowtopn;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author lixilin
 * @Date 2022/1/12 20:31
 * @Description
 */
public class TopNMapper extends Mapper<LongWritable, Text,TopNFlowBean,Text> {
    TreeMap<TopNFlowBean,Text> treeMap = new TreeMap();
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        Text phone = new Text();
        TopNFlowBean flowBean = new TopNFlowBean();
        String line = value.toString();
        String[] words = line.split("\t");
        phone.set(words[1]);
        flowBean.set(Long.valueOf(words[words.length-3]),Long.valueOf(words[words.length -2]));
        treeMap.put(flowBean, phone);
        if (treeMap.size() > 10) {
            treeMap.pollLastEntry();
        }

    }
    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        for (Map.Entry<TopNFlowBean, Text> entry : treeMap.entrySet()) {
            context.write(entry.getKey(),entry.getValue());
        }
    }
}
